package com.jugheadzhou.practice.leecode;

import java.util.Arrays;

/**
 * 给定一个数组 nums 和滑动窗口的大小 k，请找出所有滑动窗口里的最大值。
 * 输入: nums = [1,3,-1,-3,5,3,6,7], 和 k = 3
 * 输出: [3,3,5,5,6,7]
 * 解释:
 *
 *   滑动窗口的位置                最大值
 * ---------------               -----
 * [1  3  -1] -3  5  3  6  7       3
 *  1 [3  -1  -3] 5  3  6  7       3
 *  1  3 [-1  -3  5] 3  6  7       5
 *  1  3  -1 [-3  5  3] 6  7       5
 *  1  3  -1  -3 [5  3  6] 7       6
 *  1  3  -1  -3  5 [3  6  7]      7
 */
public class MovingMaxWindowTest {

    public static int[] maxSlidingWindow(int[] nums, int k) {
        int maxArrLen = nums.length - k  + 1;
        int curMaxIndex = 0;
        int[] maxArr = new int[maxArrLen];
        Integer maxVal = null;
        Integer maxValIndex = null;
        Integer secondMaxVal = null;
        Integer secondMaxValIndex = null;
        Integer thirdMaxVal = null;
        Integer thirdMaxValIndex = null;
        for (int i = 0; i < nums.length; i++) {
            int curVal = nums[i];
            if (maxVal == null || curVal >= maxVal){
                maxVal = curVal;
                maxValIndex = i;
            }else if (secondMaxVal == null || curVal >= secondMaxVal){
                secondMaxVal = curVal;
                secondMaxValIndex = i;
            }else if (thirdMaxVal == null || curVal >= thirdMaxVal){
                thirdMaxVal = curVal;
                thirdMaxValIndex = i;
            }
            if (i < k - 1){
                continue;
            }
            if (maxValIndex < i - k + 1){
                maxVal = secondMaxVal;
                maxValIndex = secondMaxValIndex;
                secondMaxVal = thirdMaxVal;
                secondMaxValIndex = thirdMaxValIndex;
                thirdMaxVal = null;
                thirdMaxValIndex = null;
            }
            maxArr[curMaxIndex] = maxVal;
            curMaxIndex += 1;
        }
        return maxArr;
    }


    public static void main(String[] args) {
//        int[] ints = MovingMaxTest.maxSlidingWindow(new int[]{1, 3, -1, -3, 5, 3, 6, 7}, 3);
//        int[] ints = MovingMaxTest.maxSlidingWindow(new int[]{1, -1}, 1);
        int[] ints = MovingMaxWindowTest.maxSlidingWindow(new int[]{9,10,9,-7,-4,-8,2,-6}, 5);
        System.out.println("ints = " + Arrays.asList(ints).toString());
    }
}
